<?php
//ResDaP
//======================
//This file contains functions that have to be defined in every page with include

//===Vars===

include 'include/server_settings.php';
/*
Not on google code, declares...

***Global variables***
$resdap_root          The full root address, "http://resources.scratchr.org" on main site.
$resdap_connected         True if there is a connection with the db

***Functions***
resdap_connect();         Connects to the database
resdap_disconnect();  Disconnects from the database - should only be used on extremely server-stressing
                      pages with a lot of calculations after the db access.
*/
//define globals
global $resdap_dev_mode,
$resdap_dev_output,
$resdap_user_rank,
$resdap_user_name,
$resdap_admin_features,
$resdap_mod_features;

//----------
$resdap_dev_mode = true; //!!!!!!!!!!!!!!  change me to false on release!!!!!!!!!!!!!!!!!!!!!
$resdap_dev_output = '';

$resdap_user_rank = 'guest';
$resdap_user_permissions = 'none';

$resdap_user_name = '';
$resdap_user_id = 0; //UID 0 does not exist

$resdap_admin_features = false;
$resdap_mod_features = false;


$resdap_connected = false;

$html_doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
$html_scripts = '<script type="text/javascript" src="/js/ResDaP.js"></script>'."\n".
                                '<script type="text/javascript" src="/js/ajax.js"></script>'."\n";
$html_css = '<link href="/css/style.css" rel="stylesheet" type="text/css">'."\n".'<link rel="icon" type="image/vnd.microsoft.icon" href="/favicon.ico">'."\n";
$html_meta ='<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>'."\n".
                        '<meta name="title" content="Scratch Resources"></meta>'."\n".
                        '<meta  name="description" content="Scratch Resources: a site to share all possible Scratch resources such as sprites, sound effects, music loops, scripts, backgrounds, tutorials"></meta>'."\n".
                        '<meta  name="author" content="The Scratch Community"></meta>'."\n".
                        '<meta  name="keywords" content="programming, youth, children, kids, novices, visual programming, video games, interactive art, sharing, online communities, user-generated content, creativity, learning, education, beginners, beginning, easy, learn, draw, drawing, fun, program, games, animation, educators, play, playful, digital expression, 21st century skills, participatory media, resdap, sprites, sounds, backgrounds, music loops, music"></meta>'."\n";
$html_meta_nosearch =
                        '<meta name="robots" content="noindex, nofollow"></meta>' ."\n".
                        '<meta name="googlebot" content="noindex, nofollow"></meta>'."\n";

global $allowed_categories;
$allowed_categories['sprites'] = 'animals fantasy letters people things transportation';
$allowed_categories['scripts'] = 'movement math lists misc';
$allowed_categories['sounds'] = 'animal effects electronic human instruments loops percussion vocals';
$allowed_categories['backgrounds'] = 'indoors outdoors nature sports';

//===Page parsing===
function write_title_box($title) {
	echo '<div id="titlebox">';
	echo '<h1>'.$title.'</h1>';
	echo '</div>';
}

function write_message_banner() {
	//write message banner function - just in case ...
}
function write_footer() {
	//Blue credits banner
	echo '<div id="footer">';
	echo '<a href="http://scratch.mit.edu">Scratch</a> is a project of the <a href="http://LLK.media.mit.edu">Lifelong Kindergarten Group</a> at the <a href="http://media.mit.edu">MIT Media Lab</a>';
	echo '</div>';
	//Google Analytics Tracker
	echo '<script src="/js/ga.js" type="text/javascript"></script>';
	echo '<script src="/js/ga2.js" type="text/javascript"></script';
}

function write_tinyresult($row, $float) {
	$q = "SELECT * FROM res_users WHERE id='".$row['user']."'";
	$user_result = mysql_query($q);
	$user_row = mysql_fetch_array($user_result);
		
	echo '<div class="tinyresult" style="float: '.$float.';">'."\n";
	echo '<div class="tinyresult_thumb"><img src="/files/images/icon_'.$row['type'].'.png"></img></div>'."\n";
	echo '<div class="tinyresult_info">';
	echo '<b>'.$row['title'].'</b> by <a href="http://scratch.mit.edu/users/'. $user_row['username'].'">'.$user_row['username'].'</a><br>'."\n";
	echo 'Category: <a href="/browse/'.$row['type'].'s/'.$row['category'].'">'.$row['category'].'</a><br>'."\n";
	echo "</div>";
	echo '<div class="tinyresult_toolbar" ';
	if ($row['type']=='sound') {
		echo 'style="width: 235px;"';
	} else {
		echo 'style="width: 255px;"';
	}
	echo "> \n";
	if ($row['type']=='background') {
		echo '<a href="javascript:previewImage('."'/download?id=".$row['id']."')".'"><img src="/files/images/tb_icon_view.png" border="0"></img></a>'."\n";
	}
	echo '<a href="/download?id='.$row['id'].'"><img src="/files/images/tb_icon_download.png" border="0"></img></a>'."\n";
	if ($row['type']=='sound') {
		echo '&nbsp;</div>';
		echo '<div class="tinyresult_player">';
		echo '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="20" height="20" id="player" align="middle">';
		echo '<param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="../files/miniplayer.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent"><param name="bgcolor" value="#ffffff"><param name="flashvars" value="song='.$row['id'].'.'.$row['ext'].'&type='.$row['category'].'">';
		echo '<embed src="../files/miniplayer.swf" quality="high" flashvars="song='.$row['id'].'.'.$row['ext'].'&type='.$row['category'].'" wmode="transparent" bgcolor="#ffffff" width="20" height="20" name="player" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></object>';
		echo '</div>';
	} else {
		echo '</div>';
	}
	echo "</div> \n";
}



//===MySQL===

function resdap_attempt_login($username, $password) {
	global $resdap_user_name, $resdap_user_rank, $resdap_user_id, $resdap_user_permissions, $resdap_connected;
	$error = false;
	
	//We're going to perform DB operations, open the connection
	resdap_connect();
	
	//validate user via ScratchR API
	$auth = scratchr_api('authenticateuser',$username,$password);
	
	//retrieve the ScratchR User ID from the result
	$scratchr_uid = $auth[0];
	
	
	if ($auth && ($auth[1]==$username) ) {
		//ScratchR account validated
		
		//check if user already exists in the SR database
		$q = "SELECT * FROM res_users WHERE username='$username'";
		$user_result = mysql_query($q);
		
		if (mysql_num_rows($user_result)!=1) {
			//add the user to the database
			resdap_register_user($username, $scratchr_uid);
			
			//retry the query now the user is created
			$q = "SELECT * FROM res_users WHERE username='$username'";
			$user_result = mysql_query($q);
		}
		
		//fetch an array from the result of the query in $user_result
		$user_row = mysql_fetch_array($user_result);
	
		//fill in the scratchr_uid if it is 0 (user registered before implementation of scratchr authentication)
		if ($user_row['scratchr_uid']==0) {
			$q = "UPDATE res_users SET scratchr_uid='$scratchr_uid' WHERE id='".$user_row['id']."'";
			$update_result = mysql_query($q);
			
			//update uid without performing a new query
			$user_row['scratchr_uid'] = $scratchr_uid;
		}
		
		//check permissions	
		$q = "SELECT * FROM res_permissions WHERE id='".$user_row['rank']."'";
		$result = mysql_query($q);
		$permissions_row = mysql_fetch_array($result);
		
		session_start();
		
		$_SESSION['user_permissions'] = $permissions_row['permissions'];
		$_SESSION['user_rank'] = $permissions_row['name'];
		$_SESSION['user_name'] = $username;
		$_SESSION['user_id']   = $user_row['id'];
		$_SESSION['user_ip']   = $_SERVER['REMOTE_ADDR'];
		
		$resdap_user_name = $_SESSION['user_name'];
		$resdap_user_rank = $_SESSION['user_rank'];
		$resdap_user_id   = $_SESSION['user_id'];
		$resdap_user_permissions = $_SESSION['user_permissions'];
		
		//update ip address in users table
		$q = "UPDATE res_users SET ip='" . $_SERVER['REMOTE_ADDR'] . "' WHERE id='" . $row['id'] . "'";
		$result = mysql_query($q);
		
		setcookie("resdap_usr_n", $_SESSION['user_name'], time()+30*24*60*60, '/'); // expire in a month
		setcookie("resdap_usr_p", base64_encode($password), time()+30*24*60*60, '/'); //
		
	} else {
		$error = true;
	}
	return $error;
}

function resdap_register_user($username, $scratchr_uid) {
	$qValues = "'$scratchr_uid', '$username', '1'";
	$q =  "INSERT INTO res_users ( scratchr_uid, username, rank) VALUES($qValues)";
	mysql_query($q);
}

function resdap_user_haspermission($permission) {
	global $resdap_user_permissions;
	$q = strpos("  $resdap_user_permissions ",$permission);
	return $q;
}

//==== ScratchR API ====

function scratchr_api($api_function, $arg1 = NULL, $arg2 = NULL , $arg3 = NULL) {
	//general Scratch API function.
	$request = "http://scratch.mit.edu/api/$api_function";
	if (isset($arg1)) $request .= "/$arg1";
	if (isset($arg2)) $request .= "/$arg2";
	if (isset($arg3)) $request .= "/$arg3";
	if (isset($arg4)) $request .= "/$arg4";
	$reply = file_get_contents($request);
	$reply = substr($reply, 3); //Bug on ScratchR side, ticket #422 on Assembla. Remove when fixed (!)
	$reply = ($reply!='false') ? explode(':', $reply) : false;
	return $reply;
}
//===========

function delcookie($cookiename) {
	setcookie($cookiename, '', time()-36000); //set negative time to remove cookie.
}
function get_arg_type($gArg) {
	global $arg;
	global $allowed_categories;
	//returns the argument type for a browse.php GET argument and also validates it
	if (preg_match('/[0-9]+/', $gArg)) {
		$argType = 'page';
	} elseif (strpos('  newest name downloads ' , ' '.$gArg.' ')) {
		$argType = 'sortby';
	} elseif (strpos('  sprites sounds backgrounds scripts ' , ' '.$gArg.' ')) {
		$argType = 'type';
	} elseif (substr($gArg, 0, 7) == 'search_') {
		$argType = 'search';
	} elseif (isset($arg['type'])) {
		if (strpos('  '.$allowed_categories[$arg['type']].' ', " $gArg ")) {
			$argType = 'category';
		}
	}
	return $argType;
}

function dev_out($output) {
	//Use this function for development purposes only, ot outputs text in a red box on the bottom of the page if
	//redsap_dev_mode is true.
	global $resdap_dev_mode, $resdap_dev_output;
	if ($resdap_dev_mode) {
	        $resdap_dev_output .= '<li>'.$output."\n";
	}
}

// =====================================

//Code here will be ran on every page

//Session handling
session_start();
if (isset($_SESSION['user_name'])) {
	//session is there, check if it's still active
	if ( $_SESSION['user_name']==$_COOKIE['resdap_usr_n'] ) {
			
		//session valid, refresh cookies
		setcookie('resdap_usr_n', $_SESSION['user_name'], time()+30*24*60*3600, '/'); // expire in a month
		setcookie('resdap_usr_p', $_COOKIE['resdap_usr_p'], time()+30*24*60*3600, '/');
		
		//set resdap variables
		$resdap_user_rank = $_SESSION['user_rank'];
		$resdap_user_name = $_SESSION['user_name'];
		$resdap_user_id   = $_SESSION['user_id'];
		$resdap_user_permissions = $_SESSION['user_permissions'];
	}
} elseif (isset($_COOKIE['resdap_usr_n']) && isset($_COOKIE['resdap_usr_p'])) {
	//there still is a login cookie on the clients PC, but there is no Session on the server.
	//try to log in again.
	dev_out('wut theres a cookie but no session =(');
	resdap_attempt_login($_COOKIE['resdap_usr_n'], base64_decode($_COOKIE['resdap_usr_p']));
}


/* DEPRECATED */
if ($resdap_user_rank == 'moderator' || $resdap_user_rank =='admin') {
	$resdap_mod_features = true;
}
if ($resdap_user_rank =='admin')         {
	$resdap_admin_features = true;
	$resdap_mod_features = true;
}
/* END DEPRECATED */

$view_exceptions = "  /login /logout ";
if (!(resdap_user_haspermission('view') || strpos($view_exceptions, ' '.$_SERVER['REQUEST_URI'].' ')>0)) {
	//Only show pages when logged in as mod or admin or beta, otherwise show login page.
	header('Refresh: 0; URL=http://resources.scratchr.org/');
	die;
}       
?>